#!/usr/bin/env bash
set -euo pipefail

# 颜色输出函数
log_info() { echo -e "\033[32m[INFO]\033[0m $*"; }
log_warn() { echo -e "\033[33m[WARN]\033[0m $*"; }
log_error() { echo -e "\033[31m[ERROR]\033[0m $*" >&2; }
log_fatal() { echo -e "\033[31m[FATAL]\033[0m $*" >&2; exit 1; }

log_info "==================================================="
log_info "PR Sentinel Container - Starting (Minimal)..."
log_info "==================================================="
log_info "Time: $(date '+%Y-%m-%d %H:%M:%S %Z')"
log_info "User: $(whoami) (UID=$(id -u), GID=$(id -g))"
log_info "Working Dir: $(pwd)"

# 1) 加载环境变量文件（如果存在）
if [[ -f /app/.env ]]; then
  log_info "Loading environment variables from /app/.env"
  while IFS= read -r line; do
    # 跳过注释和空行
    [[ "$line" =~ ^#.*$ ]] && continue
    [[ -z "$line" ]] && continue
    # 只导出有效的环境变量行
    if [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*=.*$ ]]; then
      export "$line" 2>/dev/null || true
    fi
  done < /app/.env
fi

# 2) 环境变量处理
log_info "Processing environment variables..."

# 统一API密钥变量名（优先使用ANTHROPIC_AUTH_TOKEN）
if [[ -n "${ANTHROPIC_AUTH_TOKEN:-}" ]]; then
  log_info "Using ANTHROPIC_AUTH_TOKEN as API key"
elif [[ -n "${CLAUDE_API_KEY:-}" ]]; then
  log_info "Using CLAUDE_API_KEY as API key"
else
  log_warn "No API key found (CLAUDE_API_KEY or ANTHROPIC_AUTH_TOKEN)"
  log_warn "Some features may not work without API key"
fi

# 钉钉通知检查
if [[ "${ENABLE_DINGTALK_NOTIFY:-true}" == "true" ]]; then
  if [[ -z "${DINGTALK_WEBHOOK_URL:-}" ]]; then
    log_warn "DingTalk notification enabled but DINGTALK_WEBHOOK_URL not set"
  else
    log_info "DingTalk notification enabled"
  fi
else
  log_info "DingTalk notification disabled"
fi

# Gitee Token检查
if [[ -n "${MCP_TOKEN:-}" ]]; then
  log_info "MCP_TOKEN detected"
else
  log_warn "MCP_TOKEN not set, some features may be limited"
fi

# 3) 配置 Claude CLI 和 MCP 服务
if command -v claude &> /dev/null; then
  log_info "Claude CLI found, configuring..."
  
  # Claude CLI会自动从ANTHROPIC_AUTH_TOKEN环境变量读取API密钥
  # 不需要显式配置，只需确保环境变量存在即可
  if [[ -z "${ANTHROPIC_AUTH_TOKEN:-}" ]]; then
    log_warn "ANTHROPIC_AUTH_TOKEN not set, Claude CLI may not work properly"
  else
    log_info "ANTHROPIC_AUTH_TOKEN is set, Claude CLI will use it automatically"
  fi
  
  # 配置 MCP 服务（强制使用管理器）
  MCP_SERVICE="${MCP_SERVICE:-mcp-gitee}"
  log_info "Configuring MCP service: $MCP_SERVICE"
  
  # 加载MCP管理器（必需）
  if [[ ! -f "/app/mcp/mcp-manager.sh" ]]; then
    log_fatal "MCP manager not found at /app/mcp/mcp-manager.sh"
  fi
  
  source /app/mcp/mcp-manager.sh
  
  # 加载MCP配置
  if ! load_mcp_config "$MCP_SERVICE"; then
    log_fatal "Failed to load MCP service configuration: $MCP_SERVICE"
  fi
  
  # 配置环境变量
  configure_mcp_env "$MCP_SERVICE"
  
  # 生成Claude CLI配置文件（.claude.json）
  if ! generate_claude_cli_config "$MCP_SERVICE" "/app/.claude.json"; then
    log_fatal "Failed to generate Claude CLI configuration"
  fi
  
  log_info "MCP service configuration completed: $MCP_SERVICE"
else
  log_warn "Claude CLI not found, skipping MCP configuration"
fi

# 4) 创建必需的目录
log_info "Ensuring directory structure..."
directories=(
  "logs/webhooks"
  "logs/reviews"
  "logs/debug"
  "score"
  "/tmp/pr-sentinel"
)

for dir in "${directories[@]}"; do
  if [[ ! -d "$dir" ]]; then
    mkdir -p "$dir" 2>/dev/null || true
  fi
done

# 4) 检查 webhook-runner
log_info "Checking webhook-runner..."
if [[ -f "/app/webhook-runner/webhook-runner" ]]; then
  if [[ ! -x "/app/webhook-runner/webhook-runner" ]]; then
    log_info "Setting webhook-runner executable permission..."
    chmod +x /app/webhook-runner/webhook-runner || log_error "Failed to set executable permission"
  fi
  log_info "webhook-runner binary found and ready"
else
  log_fatal "webhook-runner binary not found at /app/webhook-runner/webhook-runner"
fi

# 5) 检查和设置脚本权限
log_info "Checking script permissions..."
scripts=(
  "/app/start_review.sh"
  "/app/run.sh"
  "/app/webhook-runner/webhook-runner"
)

for script in "${scripts[@]}"; do
  if [[ -f "$script" ]] && [[ ! -x "$script" ]]; then
    chmod +x "$script" 2>/dev/null || true
  fi
done

# 设置scripts目录下所有脚本的权限
if [[ -d "/app/scripts" ]]; then
  find /app/scripts -name "*.sh" -exec chmod +x {} \; 2>/dev/null || true
fi

# 6) 显示配置摘要
log_info "==================================================="
log_info "Configuration Summary:"
log_info "==================================================="
log_info "Listen Address: ${LISTEN_ADDR:-0.0.0.0}:${LISTEN_PORT:-9002}"
log_info "Webhook Secret: $(if [[ -n "${WEBHOOK_SECRET:-}" ]]; then echo "***SET***"; else echo "NOT SET"; fi)"
log_info "MCP Service: ${MCP_SERVICE:-mcp-gitee}"
log_info "MCP Token: $(if [[ -n "${MCP_TOKEN:-}" ]]; then echo "***SET***"; else echo "NOT SET"; fi)"
log_info "Claude Config: ${CLAUDE_CONFIG_FILE:-/root/.claude/claude_desktop_config.json}"
log_info "Auto-merge: ${AUTO_MERGE_IF_LOW_RISK:-true}"
log_info "Review Standards: ${ENABLE_REVIEW_STANDARDS:-true}"
log_info "Script Timeout: ${JOB_TIMEOUT_SEC:-900}s"
log_info "==================================================="

# 7) 健康检查
log_info "Performing pre-flight checks..."

if [[ ! -f "/app/webhook-runner/webhook-runner" ]]; then
  log_fatal "webhook-runner binary not found"
fi

if [[ ! -x "/app/webhook-runner/webhook-runner" ]]; then
  log_error "webhook-runner binary not executable, trying to fix..."
  chmod +x /app/webhook-runner/webhook-runner || log_fatal "Failed to make webhook-runner executable"
fi

# 8) 信号处理
trap 'log_info "Received shutdown signal, stopping..."; exit 0' SIGTERM SIGINT SIGQUIT

# 9) 启动服务
log_info "Starting PR Sentinel webhook server..."
log_info "==================================================="

# 使用exec替换当前进程
exec /app/webhook-runner/webhook-runner